$(function() {
	$('input[type="checkbox"]').iCheck({checkboxClass: 'icheckbox_square-green'});	
	
	$('#btnSelectMsg').on('click', function(){
		$('#layer_opt_status').val(''); 
		var url = rootPath + '/wechatMsgConfig/toSelectWechatMsgConfigPage';
		var index = showDialogUrl('选择消息', 1000, 450, url, function(index){
			var optStatus = $('#layer_opt_status').val();
			if (optStatus == '1') {
			}
			layer.close(index);
		})
		layer.full(index);
	})
	
	// 客户等级下拉框
	sys.selectpicker({
		id : 'customerLevel',
		url : rootPath + '/customerLevel/listCustomerLevel',
		valueField : 'id',
		textField : 'levelName',
		defaultAll : true,
		width: '180px',
	});
	
	//初始化查询条件中的三级联动
	sys.threeLevelArea({
		provinceId : 'provinceId',
		cityId : 'cityId',
		areaId : 'areaId',
		defaultAll : true
	});
	
	initCustomerGrid();
	
	initSelectedUsersTable();
		
	$("#btn_save").click(function() {
		$("#wechatMsgMassSendingForm").submit();
		return false;
	});
	
	$("#wechatMsgMassSendingForm").validate({
		rules : {
			msgId : {
				required : true
			},
		},
		messages : {
			msgId : {
				required : '请选择消息', 
			},
		},
		errorPlacement : function(error, element) { // 错误信息位置设置方法
			var tagName = $(element).is("select");
    		if(!tagName) {
    			error.insertAfter(element);
    		}else {
    			error.insertAfter(element.parent().next());
    		}
		},
		submitHandler : function(form) {
			var data = $('#wechatMsgMassSendingTable').bootstrapTable('getData');  
			if (data.length < 2) {
				show("请至少选择两位客户");
				return false;
			}
			var openIdArr = $.map(data, function(item) {
				return item.openId;
			})
			
			if (openIdArr.length == 0) {
				return false;
			}
			$("#btn_save").hide();
			layer.msg("正在提交发送中...");
			//异步提交表单
			$(form).ajaxSubmit({
				type		: 'post',
				data		: {openIds: openIdArr.toString()},
				success		: function(json){ 
					if (json.resultCode == '1') {
						window.location.href = rootPath + "/wechatMsgMassSending/toListWechatMsgMassSendingPage";
					} else { 
						showErr("发送失败!");
						$("#btn_save").show();
					}
				},
				error: function(){
					$("#btn_save").show();
				}
			}); 
		}
	});
	
	$("#btn_back").click(function() {
		window.location.href = rootPath + "/wechatMsgMassSending/toListWechatMsgMassSendingPage";
	});
	
	$('#btnQueryUser').on('click', function(){
		$('#customerTable').bootstrapTable('uncheckAll');
		sys.reloadTable('customerTable');
	})
	
	$('#btnClearSelectUsers').on('click', function(){
		$('#customerTable').bootstrapTable('uncheckAll');
	})
	
	$("#checkAllUsers").on('click', function(){ 
		$('#customerTable').bootstrapTable('checkAll');
	}); 
	
});

/**
 * 初始化用户信息列表
 */
function initCustomerGrid(){
	// 定义列
	var columns = [
	    { checkbox: true, formatter: function(value, row, index){
	    	return  isSelectedUser(row.mobile);
	    } },
   		{ field : 'no', title : '序号', align : 'left',
   			formatter : function(value, row, index) {
   				return index + 1;
   			}
   		},
   		{ field : 'userName', title : '客户名', align : 'center', valign:'middle' },
   		{ field : 'mobile', title : '手机号码', align : 'center', valign:'middle' },
   		{ field : 'openId', visible: false },
   		];
			
			
	// 定义查询回调函数（查询参数在此设置）
	var queryParams = function(params) {
		
		return {
			rows : params.limit, // 页面大小
			page : params.pageNumber, // 页码 
			"userName"	: $("#customerName").val(),
			"mobile"	: $("#mobile").val(),
			"customerLevel"	: $("#customerLevel").selectpicker('val'),  
			"provinceCode"	: $("#provinceId").selectpicker('val'),  
			"cityCode"	: $("#cityId").selectpicker('val'),  
			"areaCode"	: $("#areaId").selectpicker('val')
		};
		
	};
	
	var url = rootPath + "/customer/listWechatCustomerPage"; // 请求json数据的服务器地址  
	sys.initTable('customerTable', {
		url : url,
		queryParams : queryParams,
		columns : columns,
		striped : true,
		clickToSelect : true,
		onCheck: function(row) {
			if (!isSelectedUser(row.mobile)) {
				$('#wechatMsgMassSendingTable').bootstrapTable('append', [{userName: row.userName, mobile: row.mobile, openId: row.openId}])
			}
		},
		onUncheck: function(row) {
			$('#wechatMsgMassSendingTable').bootstrapTable('remove', {field: 'openId', values: [row.openId]});
		},
		onCheckAll: function(rows) {
			$.ajax({
				type: 'post',
				url: url,
				data: {},
				dataType: 'json',
				success: function(result) {
					if (result.rows) {
						var data = [];
						$.each(result.rows, function(){
							data.push({userName: this.userName, mobile: this.mobile, openId: this.openId});
						})
						$('#wechatMsgMassSendingTable').bootstrapTable('load', data);
					}
				}
			})
		},
		onUncheckAll: function(rows) {
			$('#wechatMsgMassSendingTable').bootstrapTable('removeAll');
		}
	});
}

function initSelectedUsersTable(){
	var columns = [
	  { field : 'userName', title : '客户名', align : 'center', valign:'middle' },
	  { field : 'mobile', title : '手机号码', align : 'center', valign:'middle' },
	  { field : 'openId', visible: false },
	  { field : '#', title: '操作', align : 'center', formatter: function(value, row, index){
		  return "<a href='#' onclick='removeSelectedUser(\""+row.mobile+"\")'><i class='fa fa-remove fa-fw'></i><a>";
	  }}
	];
	var queryParams = function(params) {
		return {
			rows : params.limit, // 页面大小
			page : params.pageNumber, // 页码  
		};
	};
	var config = {
			queryParams : queryParams,
			sidePagination: 'client',
			columns : columns,
			striped : true,
			clickToSelect : true,
		};
	sys.initTable('wechatMsgMassSendingTable', config);
}

/**
 * 判断是否已添加用户 
 */
function isSelectedUser(mobile) { 
	var data = $('#wechatMsgMassSendingTable').bootstrapTable('getData');   
	if (data) { 
		 for (var i = 0; i < data.length; i++) {
			 if (data[i].mobile == mobile) { 
				 return true;
			 }
		 }
	}
	return false;
}

/**
 * 删除已选择的用户 
 */
function removeSelectedUser(mobile){
	$('#wechatMsgMassSendingTable').bootstrapTable('remove', {field: 'mobile', values: [mobile]});
	var data = $('#customerTable').bootstrapTable('getData');
	if (data) { 
		 for (var i = 0; i < data.length; i++) {
			 if (data[i].mobile == mobile) { 
				 $('#customerTable').bootstrapTable('uncheck', i);
				 break;
			 }
		 }
	}
}

